<template>
  <a-config-provider :locale="locale">
    <div>
      <p>新增广告</p>
      <a-form-model
        ref="ruleForm"
        :model="formInline"
        :rules="rules"
        :label-col="{ span: 2 }" 
        :wrapper-col="{ span: 12 }"
      >
        <a-form-model-item label="所属校区" ref="campus" prop="campus">
           <a-select
            v-model="formInline.campus" 
            mode="multiple" 
            :maxTagCount="1"
            placeholder="请选择校区" 
            showSearch  
            optionFilterProp="children" 
            allowClear 
            style="width: 280px"
            @change="categoryChange"
            >
              <a-select-option value="-1" key="all">全部校区</a-select-option>
              <a-select-option v-for="item in campusArr" :key="item.campusId" :value="item.campusId" :disabled="flag">
                {{ item.campusName }}
              </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="广告标题" ref="value1" prop="value1">
          <a-input v-model="formInline.value1" placeholder="仅用于后台展示，最多50字" style="width:280px;">
          </a-input>
        </a-form-model-item>
        <a-form-model-item label="有效时间" ref="time" prop="time">
          <a-range-picker v-model="formInline.time" style="width:280px;" />
          <a-tooltip placement="right">
            <template slot="title">
              <span>有效期内、上架的「广告」，才会在前端展示。</span>
            </template>
            <a-icon type="question-circle" style="font-size:20px; padding-left:5px;" />
          </a-tooltip>
        </a-form-model-item>
        <a-form-model-item label="广告图" ref="imageUrl" prop="imageUrl">
          <div style="display:flex;align-items:center;">
            <a-upload
              v-if="!formInline.imageUrl"
              name="file"
              listType="picture-card"
              class="avatar-uploader"
              :showUploadList="false"
              :beforeUpload="beforeUpload"
              :customRequest="uploadImage"
              accept="image/jpeg,image/jpg,image/png"
              style="width:112px;"
            >
              <div>
                <a-icon type="plus" />
                <div class="ant-upload-text">
                  上传
                </div>
              </div>
            </a-upload>
            <span>建议图片大小：800px * 1280px；图片大小：2M以内；图片扩展名png、jpg、jpeg。</span>
          </div>
          <a-input v-show="false" v-model="formInline.imageUrl"></a-input>
          <div v-if="formInline.imageUrl">
            <img :src="formInline.imageUrl ? formInline.imageUrl : ''" style="width:100%;"/>
            <a-button size="small" @click="delImage">删除</a-button>
          </div>
        </a-form-model-item>
        <a-form-model-item label="状态" ref="status" prop="status">
          <a-radio-group v-model="formInline.status">
              <a-radio :value="1">上架</a-radio>
              <a-radio :value="-1">下架</a-radio>
            </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 12, offset: 2 }">
          <a-button @click="back">取消</a-button>
          <a-button type="primary" style="margin-left:10px;" @click="onSubmit">确定</a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
  </a-config-provider>
</template>
<script>
import moment from 'moment';
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN';
export default {
  data(){
    return {
      locale: zhCN,
      campusArr:[], // 校区数据
      flag:false,
      formInline:{
        campus:undefined,
        value1:'',
        time:'',
        imageUrl:'',
        status:'',
      },
      rules: {
        campus:[
          { required: true, message: '必填项', trigger: 'change' },
        ],
        value1: [
          { required: true, message: '必填项', trigger: 'change' },
          { max: 50, message: '最多50字', trigger: 'blur' }
        ],
        time: [
          { required: true, message: '必选项', trigger: 'change' }
        ],
        imageUrl: [
          { required: true, message: '必选项', trigger: 'change' }
        ],
        image: [
          { required: true, message: '必选项', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '必选项', trigger: 'change' }
        ]
      }
    }
  },
  methods:{
    // 取消
    back(){
      this.$router.back(-1)
    },
    // 上传前
    beforeUpload(file){
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('只能上传jpg/png格式的广告图!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片不得大于2MB!')
      }
      return isJpgOrPng && isLt2M
    },
    /** 上传图片执行的操作 */
    uploadImage(info) { 
      const formData = new FormData()
      formData.append('file', info.file)
      this.$axios.post('/rc/file/upload',formData).then(res => {
        if(res.success){
          this.formInline.imageUrl = res.data
          this.$refs.ruleForm.validateField('imageUrl')
          this.$message.success('上传成功')
        }
      })
    },
    // 删除
    delImage(){
      this.$axios.delete(`/rc/file/delete?path=${this.formInline.imageUrl}`).then(res => {
        if(res.success){
          this.formInline.imageUrl = ''
          this.$message.success(res.message)
        }
      })
    },
    // 确定
    onSubmit(){
      this.$refs.ruleForm.validate((valid,value) => {
        if (valid) {
          this.$axios.post('/rc/api/advert/save',{
            campusId:this.formInline.campus,
            name: this.formInline.value1,
            beginTime: moment(this.formInline.time[0]).format('YYYY-MM-DD'),
            endTime: moment(this.formInline.time[1]).format('YYYY-MM-DD'),
            status: this.formInline.status,
            storeUrl: this.formInline.imageUrl
          }).then(res => {
            if(res.success){
              this.$message.success(res.message)
              this.$router.back(-1)
            }
          })
        }
      });
    },
    // 改变校区select选中
    categoryChange(value){
      if(value.length > 0){
        if(value.indexOf('-1') !== -1){
          this.flag = true
          this.formInline.campus = ['-1']
        } else {
          this.flag = false
        }
      } else {
        this.flag = false
      }
    }
  },
  created(){
    // 获取校区数据
    this.$axios('/rc/api/organization/campus').then(res => {
      if(res.success){
        this.campusArr = res.data
      }
    })
  }
};
</script>

<style lang="scss" scoped>
</style>